using KlearTweet.Client.Model;

namespace KlearTweet.Client.Initialization
{
    public class AccountsManager
    {
        private readonly System.Collections.Generic.IList<Account> _accounts;

        public AccountsManager(System.Collections.Generic.IDictionary<string, string> initParams)
        {
            _accounts = Storage.Database.LoadAccounts();

            string userName;
            string authToken;
            string applicationConsumerKey;
            initParams.TryGetValue("Account.UserName", out userName);
            initParams.TryGetValue("Account.AuthToken", out authToken);
            initParams.TryGetValue("Account.ApplicationConsumerKey", out applicationConsumerKey);

            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(authToken) && !string.IsNullOrEmpty(applicationConsumerKey))
            {
                var newAccount = new Account
                {
                    User = new User { UserName = userName },
                    AuthToken = authToken,
                    ApplicationConsumerKey = applicationConsumerKey,
                };
                // TODO: If there is another instance (will happen in OOB scenarios), send it (+ stop initialization)
                _accounts.Add(newAccount);
                Storage.Database.Save(_accounts);
            }
        }


        public System.Collections.Generic.IList<Account> GetAccounts()
        {
            return _accounts;
        }


        public void RegisterAddAccount(System.Windows.Controls.Button addAccount)
        {
            if (System.Windows.Application.Current.IsRunningOutOfBrowser) // In OOB, throws System.InvalidOperationException: The DOM/scripting bridge is disabled.
                DataContainers.InfoController.Show("This functionality is only available inside a browser. Open www.kleartweet.com"); // TODO: HyperlinkButton works in OOB, so show the link in it
            else
                addAccount.Click += (s, e) => WebServices.TwitterClient.GetAuthorizationUrl(
                    url => Infrastructure.ThreadPoolHelper.RunOnMainThread(()
                            => System.Windows.Browser.HtmlPage.Window.Navigate(new System.Uri(url), "_top")));
        }
    }
}